﻿using Examination.Args;
using Examination.Args.Request;
using Examination.Filter;
using Examination.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
using Examination.Utils;

namespace Examination.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [TypeFilter(typeof(WebVerificationFilterAttribute))]
    public class HomeController : ControllerBase
    {
        private readonly DataContext _dataContext;

        public HomeController(DataContext dataContext) => _dataContext = dataContext;

        [HttpPost]
        public IActionResult UserInfo([FromServices] IArgsExtend argsExtend)
        {
            User user = ((ArgsExtend)argsExtend).User;
            bool setPassword = user.Password.Equals(MD5Helper.GenerateMD5(MD5Helper.GenerateMD5(user.Number.Substring(user.Number.Length - 6))));
            return new JsonResult(new ResponseData() { Data = new { info = new { user.Name, user.Number, user.Class, user.Type }, setPassword } });
        }

        [HttpPost]
        public async Task<ActionResult> ExamInfo([FromBody] ListParameter parameter, [FromServices] IArgsExtend argsExtend)
        {
            var ps = await _dataContext.Papers.Where(p => p.EndTime == new DateTime()).ToListAsync();
            bool flag = false;
            for (int i = 0; i < ps.Count; i++)
            {
                var exam = await _dataContext.Examinations.Where(e => e.Id == ps[i].ExaminationId).Select(e => new { e.Time, e.EndTime }).FirstOrDefaultAsync();
                if (exam != null && (DateTime.Now - ps[i].StartTime).TotalMinutes >= exam.Time || DateTime.Now > exam.EndTime)
                {
                    ps[i].EndTime = DateTime.Now;
                    _dataContext.Papers.Update(ps[i]);
                    flag = true;
                }
            }
            if (flag)
            {
                await _dataContext.SaveChangesAsync();
            }
            User user = ((ArgsExtend)argsExtend).User;
            var exams = await _dataContext.Examinations.OrderByDescending(e => e.StartTime).Skip(parameter.Page * parameter.Size).Take(parameter.Size).ToListAsync();
            long[] ids = exams.Select(e => e.Id).ToArray();
            var papers = await _dataContext.Papers.Where(p => p.UserId == user.Id && ids.Contains(p.ExaminationId)).Select(p => new { p.ExaminationId, p.Id, p.StartTime, p.EndTime, finish = p.EndTime != new DateTime(), score = p.EndTime != new DateTime() ? p.Score : 0 }).ToListAsync();
            return new JsonResult(new ResponseData() { Data = new { exams, papers } });
        }

        [HttpPost]
        public async Task<IActionResult> SetPassword([FromBody] SetPasswordParameter parameter, [FromServices] IArgsExtend argsExtend)
        {
            User user = ((ArgsExtend)argsExtend).User;
            if (!MD5Helper.GenerateMD5(parameter.OldPassword).Equals(user.Password))
            {
                return new JsonResult(new ResponseData() { Status = 1, Msg = "修改失败，旧密码错误" });
            }
            user.Password = MD5Helper.GenerateMD5(parameter.NewPassword);
            _dataContext.Users.Update(user);
            await _dataContext.SaveChangesAsync();
            return new JsonResult(new ResponseData());
        }
    }
}
